<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2018/7/14
 * Time: 12:27
 */

namespace app\api\controller\v1;
use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\exception\ApiException;

class News extends Common
{
    /**
     * 获取某个栏目下的新闻列表数据
     * @return array
     */
    public function index()
    {
        // validate验证器的书写 , 对栏目id,page,size进行校验
        $data = input('get.');

        //这里的数据展示原理跟后台新闻列表展示有点类似,只不过app端只显示状态为1的新闻
        $whereData['status'] = config('code.status_normal');
        if(!empty($data['catid']))
        {
            $whereData['catid'] = input('get.catid',0,'intval');
        }
        //新闻搜索  TODO:问题,输入中文没有用?
        if(!empty($data['title']))
        {
            $whereData['title'] = ['like','%'.$data['title'].'%'];
        }

        //这里的获取数据最好是要try catch一下
        $this->getPageAndSize($data);
        $total = model('news')->getNewsCountByCondition($whereData);
        $news = model('news')->getNewsByCondition($whereData,$this->start,$this->size);

        $result = [
            'total'=>$total,
            'page_num'=>ceil($total / $this->size),
            'list'=>$this->getDealNews($news)
        ];
        return show(1,'ok',$result,200);
    }

    /**
     * 获取新闻详情页数据
     * 展示方式:
     * 1.走H5,给客户端一个链接
     * 2.接口
     */
    public function read()
    {
        $id = input('param.id',0,'intval');
        if(empty($id))
        {
            return new ApiException('id is empty',404);
        }
        //通过id获取新闻数据  TODO:try catch
        $news = model('news')->get($id);
        if(empty($news) || $news->status != config('code.status_normal'))
        {
            return new ApiException('不存在该新闻',404);
        }
        //每访问一次让阅读数自增一次
        try{
            model('news')->where(['id'=>$id])->setInc('read_count');
        }catch (\Exception $e){
            return new ApiException('error',400);
        }

        $cats = config('cat.lists');
        $news->catname = $cats[$news->catid];
        return show(1,'ok',$news,200);
    }
}